package com.ds.lens.collector.receive.service;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.ds.lens.collector.receive.service.dao.LensApplicationDao;
import com.ds.lens.collector.receive.service.dao.entity.LensApplication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @author WeiShaoying
 * @date 2017-5-17.
 */
@Service
@Slf4j
public class CompositService {

    @Autowired
    LensApplicationDao lensApplicationDao;

    @Value("${lens.collector.agentcache.max:1000}")
    private int cacheMaxNum;

    @Value("${lens.collector.agentcache.expire.minutes:5}")
    private int agentExpire;


    private LoadingCache<String, LensApplication> appCache;

    @PostConstruct
    public void initLocalCache() {
        appCache = CacheBuilder.newBuilder()
                .maximumSize(cacheMaxNum)
                .expireAfterWrite(agentExpire, TimeUnit.MINUTES)
                .build(new CacheLoader<String, LensApplication>() {
                    @Override
                    public LensApplication load(String appKey) throws Exception {
                        return lensApplicationDao.selectAppByAppKey(appKey);
                    }
                });
    }

    public LensApplication getAppByAppKey(String appKey) {
        if (StringUtils.isEmpty(appKey)) {
            return null;
        }
        try {
            return appCache.get(appKey);
        } catch (Exception e) {
            log.error("get App cache failed!", e);
            return null;
        }
    }


}
